<template>
  <el-card class="content">
    <el-row>
      <el-col :span="4">
        <span>用户名：</span>
        <el-input
          placeholder="请输入用户名"
          size="mini"
          style="width: 200px"
          v-model="query.userName"
          clearable
        ></el-input>
      </el-col>
      <el-col :span="6">
        <el-button class="black-button" @click="getUserByPage" size="small"
          >查询</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="addDialogVisible = true"
          >新增</el-button
        >
      </el-col>
    </el-row>
    <p class="bg-purple">用户信息列表</p>
    <el-table
      :data="userList"
      stripe
      size="small"
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column
        prop="userName"
        label="用户名"
        align="center"
        width="80px"
      >
      </el-table-column>
      <el-table-column
        prop="realName"
        label="姓名"
        align="center"
      ></el-table-column>
      <el-table-column prop="sex" label="性别" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.sex === 0">保密</span>
          <span v-if="scope.row.sex === 1">男</span>
          <span v-if="scope.row.sex === 2">女</span>
        </template>
      </el-table-column>
      <el-table-column prop="job" label="职务" align="center"></el-table-column>
      <el-table-column
        prop="company"
        label="公司"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="email"
        label="邮件"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="phone"
        label="手机号码"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="birthday"
        label="创建时间"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" width="300px">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="updateUserInfo(scope.row)"
            >修改信息</el-button
          >
          <el-button type="text" size="small" @click="delUser(scope.row.id)"
            >删除</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="resetPassword(scope.row.id)"
            >重置密码</el-button
          >
          <!-- <el-button
            type="text"
            size="small"
            @click="monitorDialogVisible = true"
            >重绑尾矿库</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
    <el-row type="flex" justify="end">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page"
        :page-sizes="[10, 15]"
        :page-size="query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-row>
    <!-- 添加弹窗 -->
    <el-dialog
      title="添加用户信息"
      :visible.sync="addDialogVisible"
      :width="dialogWidth"
    >
      <el-form
        :model="addListForm"
        ref="addListForm"
        label-width="120px"
        size="mini"
        :rules="rules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input
                style="width: 230px"
                v-model="addListForm.userName"
                placeholder="请填写用户名"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="realName">
              <el-input
                style="width: 230px"
                v-model="addListForm.realName"
                placeholder="请填写姓名"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12"
            ><el-form-item label="角色" size="mini" prop="roleId">
              <el-select
                v-model="addListForm.roleId"
                style="width: 230px"
                placeholder="请选择角色"
                ><el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="职务" size="mini" prop="job">
              <el-input
                v-model="addListForm.job"
                style="width: 230px"
                placeholder="请填写职务"
                clearable
              >
              </el-input> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="公司" size="mini" prop="company">
              <el-input
                style="width: 230px"
                placeholder="请填写公司"
                v-model="addListForm.company"
                clearable
              >
              </el-input> </el-form-item
          ></el-col>

          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="addListForm.sex" style="width: 230px">
                <el-radio
                  v-for="item in sexList"
                  :key="item.id"
                  :label="item.id"
                  >{{ item.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item></el-col
          >
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="创建时间" label-width="120px" prop="birthday">
              <el-input
                v-model="addListForm.birthday"
                style="width: 230px"
                clearable
                disabled
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="12"
            ><el-form-item label="密码" size="mini" prop="password">
              <el-input
                type="password"
                v-model="addListForm.password"
                style="width: 230px"
                placeholder="请填写密码"
                clearable
              ></el-input> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="12"
            ><el-form-item label="邮件" size="mini" prop="email">
              <el-input
                v-model="addListForm.email"
                style="width: 230px"
                placeholder="请填写邮件"
                clearable
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" size="mini" prop="phone">
              <el-input
                v-model="addListForm.phone"
                placeholder="请填写手机号码"
                style="width: 230px"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item
          class="buttonfrom"
          style="text-align: right; margin-right: 200px"
        >
          <el-button type="primary" @click="addUser">确 定</el-button>
          <el-button @click="closeDialogVisible">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改弹窗 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      :width="dialogWidth"
    >
      <el-form
        :model="editListForm"
        ref="editListForm"
        label-width="120px"
        size="mini"
        :rules="rules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input
                style="width: 230px"
                v-model="editListForm.userName"
                placeholder="请填写用户名"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="realName">
              <el-input
                style="width: 230px"
                v-model="editListForm.realName"
                placeholder="请填写姓名"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12"
            ><el-form-item label="角色" size="mini" prop="roleId">
              <el-select
                v-model="editListForm.roleId"
                style="width: 230px"
                placeholder="请选择角色"
                ><el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="职务" size="mini" prop="job">
              <el-input
                v-model="editListForm.job"
                style="width: 230px"
                placeholder="请填写职务"
                clearable
              >
              </el-input> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="公司" size="mini" prop="company">
              <el-input
                style="width: 230px"
                placeholder="请填写公司"
                v-model="editListForm.company"
                clearable
              >
              </el-input> </el-form-item
          ></el-col>

          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="editListForm.sex" style="width: 230px">
                <el-radio
                  v-for="item in sexList"
                  :key="item.id"
                  :label="item.id"
                  >{{ item.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item></el-col
          >
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="创建时间" label-width="120px" prop="birthday">
              <el-input
                v-model="editListForm.birthday"
                style="width: 230px"
                clearable
                disabled
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="12"
            ><el-form-item label="邮件" size="mini" prop="email">
              <el-input
                v-model="editListForm.email"
                style="width: 230px"
                placeholder="请填写邮件"
                clearable
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" size="mini" prop="phone">
              <el-input
                v-model="editListForm.phone"
                placeholder="请填写手机号码"
                style="width: 230px"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item
          class="buttonfrom"
          style="text-align: right; margin-right: 200px"
        >
          <el-button type="primary" @click="isEditUserInfo">确 定</el-button>
          <el-button @click="editDialogVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="重绑监测体"
      :visible.sync="monitorDialogVisible"
      width="30%"
    >
      <el-form
        :model="monitoListForm"
        ref="monitoListForm"
        label-width="120px"
        :rules="rules"
        label-position="left"
      >
        <el-form-item label="尾矿库" prop="tailingPondId">
          <el-select
            v-model="monitoListForm.tailingPondId"
            style="display: flex"
            placeholder="请选择尾矿库"
          >
            <el-option
              v-for="item in tailingList"
              :key="item.id"
              :label="item.tailingName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="buttonfrom">
          <el-button type="primary">确 定</el-button>
          <el-button @click="monitorDialogVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-card>
</template>

<script>
import moment from "moment";
import {
  getUserByPage,
  getRoleList,
  addUser,
  queryUserTailingPonds,
} from "../../../api/system-management-api";
import axios from "axios";
export default {
  name: "UserManagementChild",
  data() {
    return {
      query: {
        page: 1,
        pagesize: 10,
        userName: "",
      },
      total: null,
      userList: [],
      sexList: [
        { id: 1, name: "男" },
        { id: 2, name: "女" },
      ],
      roleList: [],
      addDialogVisible: false,
      addListForm: {
        userName: "",
        realName: "",
        roleId: null,
        job: "",
        company: "",
        email: "",
        password: null,
        phone: null,
        birthday: moment(new Date()).format("YYYY-MM-DD 00:00:00"),
        sex: 0,
      },
      editDialogVisible: false,
      editListForm: {
        userName: "",
        realName: "",
        roleId: null,
        job: "",
        company: "",
        email: "",
        password: this.password,
        phone: null,
        birthday: "",
        sex: 1,
      },
      dialogWidth: null,
      monitorDialogVisible: false,
      monitoListForm: {
        tailingPondId: null,
        unitId: sessionStorage.getItem("unitId"),
      },
      // 尾矿库列表选择
      tailingList: [],
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 0, max: 30, trigger: "blur" },
        ],
        realName: [
          { required: true, message: "请输入用户真实姓名", trigger: "blur" },
        ],
        email: [
          {
            required: true,
            message: "请输入用户邮箱，格式为:***@***.com",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          { min: 6, max: 15, message: "请输入6-15位密码", trigger: "blur" },
        ],
        phone: [
          { required: true, validator: this.checkPhone, trigger: "blur" },
        ],
        job: [{ required: true, message: "请填写用户职务", trigger: "blur" }],
        company: [{ required: true, message: "请填写公司", trigger: "blur" }],
        birthday: [{ required: true, trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
    };
  },
  created() {
    this.getUserByPage();
    this.getRoleList();
    this.UserTailingPonds();
  },
  methods: {
    // 自定义用户名验证规则
    async checkUserName(rule, value, callback) {
      if (!value) {
        return callback(new Error("不能为空"));
      } else if (value == this.roleList.userName) {
        return callback(new Error("用户名重复"));
      } else {
        callback();
      }
    },
    // 自定义手机验证规则
    checkPhone(rule, value, callback) {
      if (!value) {
        return callback(new Error("不能为空"));
      } else {
        const reg = /^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[2,5,6,7]|7[0,1,7,8]|8[0-9]|9[1,8,9])\d{8}$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    },
    // 自定义重置密码
    validatePass(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    },
    validatePass2(rule, value, callback) {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    },
    async getUserByPage() {
      const res = await getUserByPage({
        pageCount: this.query.page,
        pageSize: this.query.pagesize,
        userName: this.query.userName,
        unitId: sessionStorage.getItem("unitId"),
      });
      console.log(res);
      if (res.resultCode == "200") {
        this.userList = res.parameter.list;
        this.total = res.parameter.total;
      } else {
        this.$message({
          message: "暂无数据",
          offset: 400,
          duration: 1000,
        });
        this.userList = [];
      }
    },
    handleSizeChange(val) {
      this.query.pagesize = val;
      this.getUserByPage();
    },
    handleCurrentChange(val) {
      this.query.page = val;
      this.getUserByPage();
    },
    // 查询用户信息中的角色列表
    async getRoleList() {
      await getRoleList({
        unitId: sessionStorage.getItem("unitId"),
      }).then((res) => {
        console.log(res);
        this.roleList = res.parameter;
      });
    },
    //添加
    addUser() {
      this.$refs.addListForm.validate(async (val) => {
        if (val) {
          const formData = new FormData();
          for (const [key, value] of Object.entries(this.addListForm)) {
            formData.append(key, value);
          }
          axios({
            method: "post",
            url: "/user/addUser",
            data: formData,
          }).then((res) => {
            if (res.data.resultCode == "200") {
              this.getUserByPage();
              this.$message.success({
                message: "新增成功",
                offset: 400,
                duration: 1000,
              });
              this.$refs.addListForm.resetFields();
              this.addDialogVisible = false;
            } else if (res.data.resultCode == "400") {
              this.$message.error({
                message: "新增失败",
                offset: 400,
                duration: 1000,
              });
              this.addDialogVisible = false;
            } else if (res.data.resultCode == "423") {
              this.$message.error({
                message: "用户名重复",
                offset: 400,
                duration: 1000,
              });
              this.addDialogVisible = true;
            }
            // this.addDialogVisible = false;
          });
        } else {
          this.$message.error({
            message: "请完善表单信息",
            offset: 400,
            duration: 1000,
          });
        }
      });
      this.$refs.addListForm.resetFields();
    },
    closeDialogVisible() {
      this.addDialogVisible = false;
      this.$refs.addListForm.resetFields();
    },
    updateUserInfo(row) {
      console.log(row);
      this.editListForm.id = row.id;
      this.editDialogVisible = true;
      this.editListForm.userName = row.userName;
      this.editListForm.realName = row.realName;
      this.editListForm.roleId = row.roleId;
      this.editListForm.job = row.job;
      this.editListForm.company = row.company;
      this.editListForm.email = row.email;
      // this.editListForm.password = row.password;
      this.editListForm.phone = row.phone;
      this.editListForm.birthday = row.birthday;
      this.editListForm.sex = row.sex;
    },
    // 修改
    isEditUserInfo() {
      this.$refs.editListForm.validate((valid) => {
        if (valid) {
          const formData = new FormData();
          for (const [key, value] of Object.entries(this.editListForm)) {
            formData.append(key, value);
          }
          axios({
            method: "post",
            url: "/user/updateUser",
            data: formData,
          }).then((res) => {
            if (res.data.resultCode == 200) {
              this.getUserByPage();
              this.$message.success({
                message: "修改成功",
                offset: 400,
                duration: 1000,
              });
            } else if (res.data.resultCode == "400") {
              this.$message.error({
                message: "修改失败",
                offset: 400,
                duration: 1000,
              });
            }
            this.editDialogVisible = false;
          });
        } else {
          this.$message.error({
            message: "请完成表单",
            offset: 400,
            duration: 1000,
          });
        }
      });
    },
    //删除
    delUser(id) {
      this.$confirm("确定删除吗？")
        .then((_) => {
          axios({
            method: "get",
            url: "/user/deleteUser/" + `${id}`,
          }).then((res) => {
            if (res.data.resultCode == "200") {
              this.$message.success({
                message: "删除成功",
                offset: 400,
                duration: 500,
              });
              this.getUserByPage();
            } else if (res.data.resultCode == "400") {
              this.$message.error({
                message: "删除失败",
                offset: 400,
                duration: 1000,
              });
            }
          });
        })
        .catch((_) => {
          this.$message({
            message: "已取消删除",
            offset: 400,
            duration: 1000,
          });
        });
    },
    // 重置密码
    resetPassword(id) {
      this.$confirm("确定重置密码吗？")
        .then((_) => {
          axios({
            method: "get",
            url: "/user/resetPassword" + `${id}`,
          }).then((res) => {
            if (res.data.resultCode == "200") {
              this.getUserByPage();
              this.$message.success({
                message: "重置成功",
                duration: 1000,
              });
            } else if (res.data.resultCode == "400") {
              this.$message.error({
                message: "重置失败",
                offset: 400,
                duration: 1000,
              });
            }
          });
        })
        .catch((_) => {
          this.$message.info({
            message: "已取消重置",
            offset: 400,
            duration: 1000,
          });
        });
    },
    //尾矿库列表类型
    async UserTailingPonds() {
      const res = await queryUserTailingPonds({
        userId: sessionStorage.getItem("id"),
      });
      console.log(res);
      this.tailingList = res.parameter;
    },
    setDialogWidth() {
      var val = document.body.clientWidth;
      const def = 750; // 默认宽度
      if (val < def) {
        this.dialogWidth = "100%";
      } else {
        this.dialogWidth = def + "px";
      }
    },
  },
};
</script>

<style scoped>
.content {
  height: 87vh;
}
.black-button {
  background-color: black;
  color: white;
}

.bg-purple {
  background: #d3dce6;
  height: 30px;
  font-size: 14px;
  line-height: 30px;
  padding-left: 10px;
}

.el-button {
  font-size: 14px;
  margin-bottom: 8px;
}
.el-table {
  display: block;
  height: 67.2vh;
  overflow-y: auto;
  margin-bottom: 15px;
}
.el-table::before {
  z-index: inherit;
}
</style>
